package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-manager/chone"
	"pet-manager/modler"
	"pet-manager/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login" + username
	errCount, _ := chone.Rdb.Get(chone.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次静止登录",
		})
		return
	}
	var user modler.User
	err := modler.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		result, _ := chone.Rdb.Incr(chone.Ctx, redis_key).Result()
		if result == 2 {
			chone.Rdb.Set(chone.Ctx, redis_key, "3", time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误3次封禁2小时",
			})
			return
		}
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": user,
		})
	}

}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	prince := c.PostForm("prince")
	dog := modler.Dog{

		Name:   name,
		Title:  title,
		Prince: prince,
	}
	modler.DB.Create(&dog)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	var dog []modler.Dog

	redis_key := "list"
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Find(&dog)
		marshal, _ := json.Marshal(dog)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &dog)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": dog,
	})
	return
}
